package org.yy.mdns;

import android.net.nsd.NsdServiceInfo;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NSDDeviceAdapter extends RecyclerView.Adapter<NSDDeviceAdapter.ViewHolder> {
    private List<NsdServiceInfo> devices = new ArrayList<>();


    public void addDevice(NsdServiceInfo device){
        devices.add(device);
        notifyItemInserted(devices.size()-1);
    }

    public void removeDevice(NsdServiceInfo device){
        Iterator<NsdServiceInfo> iterator = devices.iterator();
        boolean hasRemoved = false;
        while (iterator.hasNext()){
            NsdServiceInfo tmp = iterator.next();
            if(tmp.getServiceName().equals(device.getServiceName())){
                iterator.remove();
                hasRemoved = true;
            }
        }
        if(hasRemoved) {
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public NSDDeviceAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new ViewHolder(new TextView(viewGroup.getContext()));
    }

    @Override
    public void onBindViewHolder(@NonNull NSDDeviceAdapter.ViewHolder viewHolder, int i) {
        NsdServiceInfo serviceInfo = devices.get(i);
        viewHolder.textView.setText(serviceInfo.toString());
    }

    @Override
    public int getItemCount() {
        return devices.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        protected TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }

    public interface ItemClick{
        void onClick(NsdServiceInfo nsdServiceInfo);
    }

}
